﻿module Sustainalytics.Common {

    // Paged list of items.
    export class PagedList<TItem>
    {
        // Paged items.
        public items: TItem[] = new Array();

        // Total items count.
        public totalItemsCount: number = 0;

        // Total page count.
        public totalPageCount: number = 0;

        public pagingOptions: PagingOptions;


        // create paged list
        public static createPagedList<TItem>(items: TItem[], skip: number, take: number, totalItemsCount: number): PagedList<TItem> {
            var pagedList = new PagedList<TItem>();
            pagedList.items = items;
            pagedList.totalItemsCount = totalItemsCount;
            pagedList.totalPageCount = Math.ceil(totalItemsCount / take);
            pagedList.pagingOptions = new PagingOptions(Math.ceil(skip / take) + 1, take);

            return pagedList;
        }

        // create paged list from promises
        public static createPagedListFromPromises<TItem>($q: ng.IQService, itemsPromise: ng.IPromise<TItem[]>, skip: number, take: number, totalItemsCountPromise: ng.IPromise<number>): ng.IPromise<PagedList<TItem>> {

            var items: TItem[];
            itemsPromise.then(function (itemsRes) {
                items = itemsRes;
            });

            var totalItemsCount: number;
            totalItemsCountPromise.then(function (totalItemsCountRes) {
                totalItemsCount = totalItemsCountRes;
            });

            var def = $q.defer();

            $q.all([itemsPromise, totalItemsCountPromise])
                .then(
                // success
                function () {
                    var pagedList = PagedList.createPagedList(items, skip, take, totalItemsCount);
                    def.resolve(pagedList);
                },
                // error
                function (reason) {
                    def.reject(reason);
                });

            return def.promise;

        }
    }
}